#region Namespaces

using System.Collections.Generic;
using System.Text;

using Vibstudio.X4NET.Collections;

#endregion

namespace Vibstudio.X4NET.Csv
{
    public class CsvBuilder
    {
        public static string ComposeHeaderFromKeyValuePairs(IEnumerable<KeyValuePair> pairs)
        {
            var builder = new StringBuilder();

            foreach (KeyValuePair pair in pairs)
            {
                builder.AppendFormat("{0};", pair.Key);
            }

            return builder.ToString().Substring(0, builder.Length - 1);
        }

        public static string ComposeRowFromKeyValuePairs(IEnumerable<KeyValuePair> headerPairs,
                                                         DefaultKeyValuePairCollection rowPairs,
                                                         DefaultKeyValuePairCollection group = null)
        {
            var builder = new StringBuilder();

            foreach (KeyValuePair headerPair in headerPairs)
            {
                if (group == null)
                {
                    builder.AppendFormat("{0};", rowPairs.GetUniqueValue(headerPair.Key, headerPair.ID));
                }
                else
                {
                    if (group.ContainsKey(headerPair.Key))
                    {
                        builder.AppendFormat("{0};",
                                             group.GetFirstValue(headerPair.Key));
                    }
                    else
                    {
                        builder.AppendFormat("{0};",
                                             rowPairs.ContainsKey(headerPair.Key)
                                                 ? rowPairs.GetFirstValue(headerPair.Key)
                                                 : string.Empty);
                    }
                }
            }

            return builder.ToString().Substring(0, builder.Length - 1);
        }
    }
}